//
//  UIColor+Extesion.swift
//  XMGTV
//
//  Created by 崔博 on 2017/4/16.
//  Copyright © 2017年 coderwhy. All rights reserved.
//

import UIKit

extension UIColor {

    // 只够构造便利构造函数
    convenience init(r: CGFloat, g: CGFloat, b: CGFloat,alpha:CGFloat = 1) {
        self.init(red: r / 255.0,green: r / 255.0,blue: r / 255.0,alpha:alpha)
    }
    
    convenience init?(hex: String, alpha: CGFloat = 1.0){
        
        // 判断字符长度是否符合
        guard hex.characters.count >= 6 else {
            return nil
        }
        
        // 将字符串转成大写
        var tempHex = hex.uppercased()
        
        // 判断开头：0x/#/## || te
        if tempHex.hasPrefix("0x") || tempHex.hasPrefix("##") {
            tempHex = (tempHex as NSString).substring(to: 2)
        }
        if tempHex.hasPrefix("#") {
            tempHex = (tempHex as NSString).substring(to: 1)
        }
        // 分别去除rgb
        var rangge = NSRange(location: 0, length: 2)
        let rHex = (tempHex as NSString).substring(with: rangge)
        
        rangge.location = 2
        let gHex = (tempHex as NSString).substring(with: rangge)
        rangge.location = 4
        let bHex = (tempHex as NSString).substring(with: rangge)
        
        // 将16进制转成数字
        var r: UInt32 = 0
        var g: UInt32 = 0
        var b: UInt32 = 0
        Scanner(string: rHex).scanHexInt32(&r)
        Scanner(string: gHex).scanHexInt32(&g)
        Scanner(string: bHex).scanHexInt32(&b)
        
        self.init(r:CGFloat(r),g:CGFloat(g),b:CGFloat(b))
    }
    class func randomColor() -> UIColor {
        
       return UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256)))
    }
}
